package com.bw.coupon.consumer;

import com.alibaba.fastjson.JSONObject;
import com.bw.common.core.utils.StringUtils;
import com.bw.common.redis.service.RedisService;
import com.bw.coupon.domain.Order;
import com.bw.coupon.service.OrderService;
import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class ConsumerAll {

    @Autowired
    private RedisService redisService;

    @Autowired
    @Qualifier(value = "lua-inventory-num")
    private RedisScript<Long> luaInventoryNum;

    @Autowired
    private OrderService orderService;

    //下单失败
    private static final Integer FAIL = 0;

    //下单成功
    private static final Integer SUCCEED = 2;
    /**
     * 异步下单
     * @param jsonOrder
     */
    @RabbitListener(queuesToDeclare = {@Queue(name = "placeOrder")})
    public void placeOrderConsumer(String jsonOrder) {
        try {
            // 1. 将json字符串转换为对象
            Order order = JSONObject.parseObject(jsonOrder, Order.class);

            // 1. 获取redisTemplate
            RedisTemplate redisTemplate = redisService.redisTemplate;

            List<String> collect = order.getSkuIds().stream().map(skuId -> skuId.toString()).collect(Collectors.toList());

            // 2. 执行lua脚本
            Long execute = (Long) redisTemplate.execute(luaInventoryNum,collect, order.getSkuNums().toArray());

            // 3. 获取返回结果
            if(execute == 0){

                redisService.setCacheObject("placeOrder:"+order.getOrderNumber(),FAIL);

            }else {

                orderService.addOrder(order);

                redisService.setCacheObject("placeOrder:"+order.getOrderNumber(),SUCCEED);
            }
        }catch (Exception e){
            System.out.println(e);
            throw new RuntimeException(e);
        }
    }

}
